import React, { Component, Fragment } from 'react'
import { Form, Input, Button, Select, message, Card } from 'antd';
import { getcategory, addproduct, getinfo, editproduct ,deleteimg} from '../../api/index'
import './add.less'
import { Link, Redirect } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';
import UpdateImg from './update-img';
import RichTextEditor from './rich-text-editor'
import memoryUtils from '../../utils/memoryUtils'
const Item = Form.Item
const { TextArea } = Input;
const Option = Select.Option;


export default class AddUpdate extends Component {
  state = {
    data0: [],
    data1: [],
    categoryname: "",
    pCategoryname: '',
    loading: true
  }
  imgRef = React.createRef();
  formRef = React.createRef();
  detailRef=React.createRef();
  onFinish = async (value) => {
    const imgs = this.imgRef.current.getimgs()
    const detail=this.detailRef.current.getdetail()
    const state = memoryUtils.product
    const result = state._id === undefined ? await addproduct(value.categoryId, value.pCategoryId, value.name, value.price, detail, value.desc, imgs) :
      await editproduct(state._id, value.categoryId, value.pCategoryId, value.name, value.price, detail, value.desc, imgs)
    if (result.status === 0) {
      message.success((state._id === undefined ? '添加' : '修改') + '成功!即将返回')
      console.log(state);
      
      if (!!state._id) {
        state.imgs.map(async(item) => {
          let isIn=false
          imgs.map((img) => {
            if (img === item) {
              isIn=true
            }
            return ()=>{}
          })
          if (isIn === false) {
            await deleteimg(item)
          }
          return ()=>{}
        })
      }
      setTimeout(() => {
        this.props.history.replace('/product')
      }, 1000)
    } else {
      message.error((state._id === undefined ? '添加' : '修改') + '失败')
    }
  }
  extraImg = () => {
    if (memoryUtils.product._id === undefined) {
      const imgs = this.imgRef.current.getimgs()
      imgs.map(async(img) => {
      await deleteimg(img)
      })
      
    }
  }
  async componentDidMount() {
    const state = memoryUtils.product
    if (memoryUtils.product.pageNum === undefined) {
      return
    }
    const result = await getcategory(0)
    if (result.status === 0) {
      this.setState({ data0: result.data })
    }
    if (state.name === undefined) {
      this.setState({ loading: false })
      return
    }
    const results = await Promise.all([getcategory(state.pCategoryId), getinfo(state.pCategoryId), getinfo(state.categoryId)])
    if (results[0].status === 0 && results[1].status === 0 && results[2].status === 0) {
      this.setState({
        data1: results[0].data, pCategoryname: results[1].data.name,
        categoryname: results[2].data.name, loading: false
      })
    } else {
      message.error('获取失败')
    }
  }
  render() {
    if (memoryUtils.product.pageNum === undefined) {
      return <Redirect to='/product' />
    }
    const state = memoryUtils.product
    const { loading } = this.state
    const unstate = { pCategoryId: undefined, categoryId: undefined, name: undefined, price: undefined, desc: undefined, detail: undefined }
    const { pCategoryId, categoryId, name, price, desc, detail, imgs } = state === undefined ? unstate : state
    const fromItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 }
    }
    return (
      <Card style={{ height: '100%', overflow: 'auto' }}
        title={(
        <Fragment>
          <Link onClick={this.extraImg} to={{ pathname: '/product', state: { pageNum: state.pageNum, pageSize: state.pageSize } }}><ArrowLeftOutlined /></Link>
          &nbsp;&nbsp;&nbsp;
          {state._id === undefined ? '添加商品' : '修改商品'}
        </Fragment>
      )}
        loading={loading}>
        <Form {...fromItemLayout}
          preserve={false} ref={this.formRef} onFinish={this.onFinish}
          initialValues={{ pCategoryId, categoryId, name, price, desc }}>
          <Item name='pCategoryId' label='所属一级分类'
            rules={[{ required: true, message: '一级分类必须选择！' }]}>
            <Select placeholder='请选择一级分类'
              onSelect={async (LabeledValue, option) => {
                const result = await getcategory(LabeledValue)
                this.setState({ data1: result.data })
                this.formRef.current.setFieldsValue({ 'categoryId': result.data.length > 0 ? result.data[0]._id : '' })
              }}
            >
              {
                this.state.data0.map((item) => {
                  return (
                    <Option key={item._id} value={item._id}>{item.name}</Option>
                  )
                })
              }
            </Select>
          </Item>

          <Item name='categoryId' label='所属二级分类'
            rules={[{ required: true, message: '二级分类必须选择！' }]}>
            <Select placeholder='请选择二级分类'>
              {
                this.state.data1.map((item) => {
                  return (
                    <Option key={item._id} value={item._id}>{item.name}</Option>
                  )
                })
              }
            </Select>
          </Item>
          <Item name='name' label='商品名称'
            rules={[{ required: true, message: '商品名称必须填写！' }]}>
            <Input autoComplete={'off'} placeholder='请输入分类名称' onPressEnter={this.props.updatedata} />
          </Item>

          <Item name='price' label='商品价格'
            rules={[
              () => ({
                validator(_, value) {
                  if (value > 0) {
                    return Promise.resolve();
                  }
                  return Promise.reject('商品价格必须大于0');
                },
              })]}>
            <Input type='number'
              autoComplete={'off'} placeholder='请输入商品价格' onPressEnter={this.props.updatedata} addonAfter='元' />
          </Item>

          <Item name='desc' label='商品描述'>
            <TextArea autoSize />
          </Item>
          <Item name='imgs' label='商品图片'>
            <UpdateImg ref={this.imgRef} imgs={imgs} isAdd={state._id}/>
          </Item>
          <Item name='detail' label='商品详情'
            wrapperCol={{ span: 20 }}>
            <RichTextEditor ref={this.detailRef} datail={detail} />
          </Item>
          <Item wrapperCol={{ offset: 10 }}>
            <Button type="primary" htmlType="submit">提交</Button>
          </Item>
        </Form>
      </Card>
    )
  }
}
